<template>
  <div class="hello">
    <!-- 图表的容器 -->
    <div ref="chartContainer" class="chartContainer"></div>
  </div>
</template>

<script>
import axios from 'axios'
//引入echarts折线图
import * as echarts from 'echarts/core';
import { GridComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([GridComponent, LineChart, CanvasRenderer, UniversalTransition]);

import dayjs from 'dayjs'//引入dayjs
import {KEY, API_24H} from "@/common/constrants";
import { mapState, mapActions } from 'vuex';

export default {
  name: 'Hour24Weather',
  // data(){
  //   return{
  //     hourly:[],
  //     hourlyWeatherData:{
  //       fxTime:[],//x轴数据，xAxisData
  //       temp:[],//seriesData
  //     }
  //   }
  // },
  computed:{
    ...mapState([
      "location",
      "hour24"
    ])
  },
  watch:{
    location:function(){
      this.getData();
    }
  },
  created(){
    this.getData();
  },
  methods:{
    ...mapActions([
      'updateHour24Action'
    ]),
    getData(){
      axios.get(API_24H,{
        params:{
          key:KEY,
          location:this.location.id,//等价于this.$store.state.location.id
          
        }
      }).then(res => {
        console.log(res.data);
        let hour24Data = {
          fxTime: [],//x轴数据，xAxisData
          temp:[],//seriesData
      }
        // this.hourly = res.data.hourly;
        res.data.hourly.forEach(element => {
          hour24Data.fxTime.push(element.fxTime)
          hour24Data.temp.push(element.temp)
        });
        //当24小时的数据做了变化之后，需要更新到state中
        this.updateHour24Action(hour24Data)//等价于this.$store.dispatch('updateHour24Action', hour24Data)


        // array.map方法
        // 箭头函数1
        // let array = this.hourlyWeatherData.fxTime.map((date)=>{
        //   return dayjs(date).format("HH")
        // })
        // 箭头函数2
        // let array = this.hourlyWeatherData.fxTime.map(date => dayjs(date).format("HH"))
        // console.log(array)
        this.initChart(
          this.hour24.fxTime.map(date => dayjs(date).format("HH")),
          this.hour24.temp)
      })
    },
    //初始化图表
    initChart(xAxisData,seriesData){
      var chartDom = this.$refs.chartContainer;
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        xAxis: {
          type: 'category',
          data: xAxisData
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: seriesData,
            type: 'line'
          }
        ]
      };

      option && myChart.setOption(option);

    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.chartContainer{
  height: 200px;
}
</style>
